package com.wjq.pay.config;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
public class AlipayService {

    @Autowired
    private PayConfig payConfig;

    public String getQrCode(String orderNo) throws AlipayApiException {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(payConfig.getUrl());
        certAlipayRequest.setAppId(payConfig.getAppid());
        certAlipayRequest.setPrivateKey(payConfig.getAppPrivateKey());
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(payConfig.getAppCertPath());

        certAlipayRequest.setAlipayPublicCertPath(payConfig.getAlipayCertPath());
        certAlipayRequest.setRootCertPath(payConfig.getAlipayRootCertPath());
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
//        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.getUrl(), payConfig.getAppid(), payConfig.getAppPrivateKey(), "json", "utf-8", payConfig.getAlipayPublicKey(), "RSA2");

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
        Map<String,String> maps = new HashMap();
        maps.put("out_trade_no",orderNo);
        maps.put("total_amount","100");
        maps.put("subject","Iphone6 16G");
        maps.put("store_id","NJ_001");
        maps.put("timeout_express","3600m");
        request.setBizContent(JSON.toJSONString(maps));
        //设置回调的url地址 关键
        request.setNotifyUrl(payConfig.getCallBackUrl());
        AlipayTradePrecreateResponse response = alipayClient.certificateExecute(request);
        System.out.print(response.getBody());
        String qrcode = response.getQrCode();
        return qrcode;
    }

    /**
     *  查询订单状态
     *  交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、
     *  TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、
     *  TRADE_SUCCESS（交易支付成功）、
     *  TRADE_FINISHED（交易结束，不可退款）
     * @param orderNo
     * @return
     * @throws AlipayApiException
     */
    public String queryOrderStatus(String orderNo) throws AlipayApiException {


        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(payConfig.getUrl());
        certAlipayRequest.setAppId(payConfig.getAppid());
        certAlipayRequest.setPrivateKey(payConfig.getAppPrivateKey());
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(payConfig.getAppCertPath());

        certAlipayRequest.setAlipayPublicCertPath(payConfig.getAlipayCertPath());
        certAlipayRequest.setRootCertPath(payConfig.getAlipayRootCertPath());

        //封装请求信息
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();


        Map<String, String> maps = new HashMap<String, String>();

        maps.put("out_trade_no",orderNo);

        //封装请求参数
        request.setBizContent(JSON.toJSONString(maps));

        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);

        //判断接口是否调用成功
        if(!response.isSuccess()){
            log.error("订单查询接口调用失败!");
            return null;
        }
        log.info("订单查询接口调用成功!");

        return response.getTradeStatus();
    }

}
